<template>
  <div class="w">

    <!-- 表单区 -->
    <Form style="padding-top: 35px;" 
      name="form" 
      ref="formRef" 
      :labelCol="{ span: 6 }" 
      :wrapperCol="{ span: 18 }" 
      :initialValues="form"
      @finish="formFinish">

      <Row>
        <Col :span="20" :offset="0">
          <FormItem name="userName" label="用户名称" :rules="formRules.username">
            <Input placeholder="请输入用户名称" style="width: 100%"/>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col :span="20" :offset="0">
          <FormItem name="nickName" label="用户昵称" :rules="formRules.nickname">
            <Input placeholder="请输入用户昵称" style="width: 100%" />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col :span="20" :offset="0">
          <FormItem name="status" label="状态">
            <Switcher type="text" />
          </FormItem>
        </Col>
      </Row>
        <Row>
        <Col :span="20" :offset="0">
          <FormItem label="角色" style="position: relative;" class="rolePopupContainer">
            <Select placeholder="请选择角色" type="multiple" :getPopupContainer="getRolePopupContainer" style="width:100%" :value="modalValue" @change="selectOnChange" allowClear>
              <Option v-for="item in currRow.roleOptions" :key="item.roleId" :value="item.roleId + ''" :label="item.roleName" :disabled="item.status == 1"/>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-if="id==0">
        <Col :span="20" :offset="0">
          <FormItem name="password" label="用户密码" :rules="formRules.password">
            <Input type="password" placeholder="请输入用户密码" style="width: 100%" />
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col :span="20" :offset="0">
          <FormItem name="phonenumber" label="手机号码">
            <Input placeholder="请输入手机号码" style="width: 100%" />
          </FormItem>
        </Col>
      </Row>
      <Row style="margin-top: 20px;">
        <Col :span="12" :offset="6">
          <FormItem :wrapperCol="{ span: 24 }" style="text-align: center">
            <Button style="width: 100px;" type="primary" @click="formValidate">提 交</Button>
            <Button style="width: 100px; margin-left: 20px;" @click="formCancel">取 消</Button>
          </FormItem>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import * as ruoyi from '@/utils/ruoyi'
import { Message } from '@uni/vue';
import { addUser, updateUser, getUser } from "@/api/system/user";
export default {
  name: "app",
  props: {
    id: {
      type: Number,
      default: 0
    },
    currRow: {
      default: () => {}
    },
    refData: {
      default: () => {}
    }
  },
  data() {
    return {
      form: {
        userName: this.currRow.userName,
        nickName: this.currRow.nickName,
        status: this.currRow.status == "0" ? true : false,
        password: this.currRow.password,
        phonenumber: this.currRow.phonenumber,
        remark: this.currRow.remark
      },
      modalValue: this.currRow.roleIds?this.currRow.roleIds:'',
      formRules: {
        username: [{ required: true, message: "请输入角色名称" }],
        nickname: [{ required: true, message: "用户昵称不能为空" }],
        password: [
          { required: true, message: "用户密码不能为空" },
          {
            validator: (rule, value) => {
              if (!value) {
                return Promise.reject(new Error("用户密码不能为空"));
              } else if (value.length < 5 || value.length > 20) {
                return Promise.reject(new Error("密码长度必须在5-20之间"));
              } else {
                return Promise.resolve();
              }
            },
          },
        ],
      },
    }
  },
  mounted() {
     if (this.id !== 0) this.queryDetail();
  },
  methods: {
    getRolePopupContainer: function () {
      return document.querySelector('.rolePopupContainer');
    },
    async queryDetail() {
      const rs = await getUser(this.id);
      if (rs.code !== 200) return Message.error({ text: '获取用户信息明细失败：' + rs.msg });
      if (rs.roleIds.length > 0)
        this.modalValue = rs.roleIds.join(',').split(',');
    },
    formValidate: function () {
      this.$refs.formRef.submit();
    },
    formCancel: function () {
      // this.$refs.formRef.reset();
      this.handleCancel();
    },
    formFinish: function (formValues) {
      this.form = formValues;
     this.formSubmit()
    },
    async formSubmit() {
      // 公共属性
      this.form.createBy = this.$store.state.user.name;
      this.form.createTime = ruoyi.parseTime(Date.now());
      this.form.updateBy = this.$store.state.user.name;
      this.form.updateTime = ruoyi.parseTime(Date.now());

      // 提交表单请求
      this.isModalVisible = false;
      let reqForm = JSON.parse(JSON.stringify(this.form));
      // console.log("reqForm: ", reqForm);
      reqForm.status = reqForm.status === true ? "0" : "1";
      reqForm.roleIds = this.modalValue === ''?[]:this.modalValue
      if (this.id) {
        // 修改
        reqForm.userId = this.id;
        const rs = await updateUser(reqForm);
        if (rs.code !== 200) return Message.error({ text: '修改用户信息失败：' + rs.msg });
        Message.success({ text: '修改用户信息完成' });
        this.handleCancel();

      } else {
        // 新增
        const rs = await addUser(reqForm);
        if (rs.code !== 200) return Message.error({ text: '新增用户信息失败：' + rs.msg });
        Message.success({ text: '新增用户信息完成' });
        this.handleCancel();
      }
    },
    handleCancel: function () {
      this.$emit('handleCancel');
    },
    selectOnChange(val) {
      this.modalValue = val;
    },
  }
}
</script>

<style scoped>
  .w {
    background-color: #F9FAFB;
  }

  /* 标题 */
  .title-area span {
    display: inline-block;
    font-weight: 500;
    line-height: 36px;
    margin-left: 15px;
  }
</style>
